package com.carlyang.jspservlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class loginFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpSession session = request.getSession();
		Object object = session.getAttribute("currentUser");
		String servletPath = request.getServletPath();
		String requestURI = request.getRequestURI();
		System.out.println("servletPath="+servletPath+",requestURI="+requestURI);
		if (object == null && servletPath.indexOf("main")>0) {//没有登录成功 且不是登录请求
			System.out.println("没有登录，转发跳转到登录页面！");
			((HttpServletResponse)servletResponse).sendRedirect("login.jsp");
			//request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
			
		}else {
			//System.out.println("存在登录事件，传递给下一个Filter处理");
			filterChain.doFilter(servletRequest, servletResponse);
			//作用是将请求转发给过滤器链上下一个对象。这里的下一个指的是下一个filter，如果没有filter那就是你请求的资源。 一般filter都是一个链,web.xml 里面配置了几个就有几个。一个一个的连在一起 
			//request -> filter1 -> filter2 ->filter3 -> .... -> request resource.
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("loginFilter过滤器初始化");
	}
	
}
